### This script will receive an argument from a .sh file, which is year
### All BRT ASCII's for that year will be read in and stored in a single dataframe
### That data frame will be saved as a .csv file
### This is an intermediate step in the extreme weather analysis

# Obtain command line arguments from .sh file

args=(commandArgs(TRUE))

# Evaluate the arguments for use in this script

for(i in 1:length(args)) 
	
	{
		
	eval(parse(text=args[[i]]))
 
	}


### Library

library('SDMTools')

### Base dir

base.dir = '/home/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/brtpredsfinal/maxgzip/'

### Load object with base.asc and base.pos

load('/home/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/brtpredsfinal/maxgzip/baseascdata.Rdata')

### List files to intersect

tfiles = list.files(paste(base.dir,yearx,sep=''),pattern='.asc.gz',full.names=T,recursive=T)

### Create an object 'outdata' to bind data onto

outdata = base.pos

### Position tracker

i=1

for (tfile in tfiles)

	{
	
	### Read in an ASCII
	
	tasc = read.asc.gz(tfile)
	
	### Extract data from points in base.pos
	
	tdata = extract.data(cbind(base.pos[,3],base.pos[,4]),tasc)
	
	### Bind to outdata
			
	outdata = cbind(outdata,tdata)
	
	#### Change the name of the newly bound column

	names(outdata)[i+4]=paste(substr(tfile,nchar(tfile)-14,nchar(tfile)-7),sep='')
	
	### Change position tracker
	
	i=i+1
	
	#### Report progress
	
	cat('\n',i,'\n')
	
	}
	
### Close loop
	
### Write outdata to the appropriate directory

write.csv(outdata,file=paste(base.dir,yearx,'/allpos_alldays_maxtemp_',yearx,'.csv',sep=''), row.names=F)	
	
### Now try fitting a distribution to outdata
### Get this upya

#quantiles(outdata[1,3:367],probs=c(90,95,99)/100,type=8,na.rm=T)
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			